package com.github.cakin.shiro.chapter5.hash.realm;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

/**
 * @className: MyRealm2
 * @description: 该 Realm 配合 HashedCredentialsMatcher 实现密码验证服务
 * @date: 2020/5/18
 * @author: cakin
 */
public class MyRealm2 extends AuthorizingRealm {
    /**
     * 功能描述：获取授权信息
     *
     * @author cakin
     * @date 2020/5/18
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        return null;
    }

    /**
     * 功能描述：获取认证信息
     *
     * @author cakin
     * @date 2020/5/18
     * @param token 传入的token
     * @return AuthenticationInfo 认证信息
     * @description: 注意：每次打印不一样
     * 8b0776ca70b173fef410309c863d80a4
     * 0eb68d8570c0d6a98065bb63a1edb265
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String username = "liu"; //用户名及salt1
        // 第一组
        // String salt2 = "0072273a5d87322163795118fdd7c45e"; // 由伪随机数器生成器生成
        // String password = "be320beca57748ab9632c4121ccac0db"; // 加密后的密码
        // 第二组
        String salt2 = "8b0776ca70b173fef410309c863d80a4"; // 由伪随机数器生成器生成
        String password = "0eb68d8570c0d6a98065bb63a1edb265"; // 加密后的密码
        SimpleAuthenticationInfo ai = new SimpleAuthenticationInfo(username, password, getName());
        ai.setCredentialsSalt(ByteSource.Util.bytes(username+salt2)); // 盐是用户名+随机数
        // HashedCredentialsMatcher 会自动根据 AuthenticationInfo 的类型是否是 SaltedAuthenticationInfo
        // 来获取 credentialsSalt 盐
        return ai;
    }
}
